import React, { useState, useEffect } from 'react';
import { Table, Tag, Space, Spin, Typography, message } from 'antd';
import { TrophyOutlined, CrownOutlined } from '@ant-design/icons';
import { contestService } from '@/services/contestService';
import { Contest, ContestRankingItem } from '@/types/contest';
import { PaginatedResponse } from '@/types/common';
import styles from './ContestRanking.module.css';

const { Text } = Typography;

interface ContestRankingProps {
  contest: Contest;
}

// 使用已定义的类型，不再需要重复定义

const ContestRanking: React.FC<ContestRankingProps> = ({ contest }) => {
  const [loading, setLoading] = useState(false);
  const [rankings, setRankings] = useState<ContestRankingItem[]>([]);
  const [problemIds, setProblemIds] = useState<string[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
    hasNext: false,
    hasPrevious: false,
  });

  useEffect(() => {
    if (contest?.id) {
      fetchRankings(1, pagination.pageSize);
    }
  }, [contest?.id]);

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    const newPageSize = pageSize || pagination.pageSize;
    fetchRankings(page, newPageSize);
  };

  const fetchRankings = async (page = 1, pageSize = 20) => {
    try {
      setLoading(true);
      const response = await contestService.getContestRankings({ 
        contest_id: contest.id,
        page,
        limit: pageSize
      });
      const responseData = response.data;
      
      // 新的API响应格式：responseData.data.data 包含分页数据
      if (responseData.code === 200 && responseData.data?.data?.results) {
        setRankings(responseData.data.data.results);
        
        // 更新分页信息
        const paginationData = responseData.data.data;
        setPagination({
          current: paginationData.current_page,
          pageSize: paginationData.page_size,
          total: paginationData.count,
          hasNext: paginationData.has_next,
          hasPrevious: paginationData.has_previous,
        });
        
        // 从第一个参赛者的submission_info中获取所有题目ID
        if (paginationData.results.length > 0) {
          const problemIds = Object.keys(paginationData.results[0].submission_info || {});
          setProblemIds(problemIds);
        }
      } else {
        message.warning('暂无排名数据');
      }
    } catch (error) {
      console.error('获取排行榜失败:', error);
      message.error('获取排行榜失败');
    } finally {
      setLoading(false);
    }
  };

  // 格式化时间显示
  const formatTime = (seconds: number) => {
    if (seconds === undefined || seconds === null) return '-';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    
    if (hours > 0) {
      return `${hours}小时${minutes}分钟`;
    }
    return `${minutes}分钟`;
  };

  // 显示排名图标
  const renderRankIcon = (rank: number) => {
    switch (rank) {
      case 1:
        return <CrownOutlined style={{ color: '#FFD700', fontSize: '20px' }} />;
      case 2:
        return <CrownOutlined style={{ color: '#C0C0C0', fontSize: '20px' }} />;
      case 3:
        return <CrownOutlined style={{ color: '#CD7F32', fontSize: '20px' }} />;
      default:
        return rank;
    }
  };

  // 处理题目ID显示
  const getProblemDisplayLabel = (problemId: string) => {
    // ACM赛制通常使用字母标识题目，如A、B、C...
    if (problemId.startsWith('_')) {
      // 使用_id属性
      const pureProblemId = problemId.substring(1); // 去掉前缀_
      const index = parseInt(pureProblemId);
      if (!isNaN(index)) {
        return String.fromCharCode(65 + index - 1); // A的ASCII码是65
      }
      return pureProblemId;
    } else {
      // 对于其他ID格式
      const index = parseInt(problemId);
      if (!isNaN(index)) {
        return String.fromCharCode(65 + index - 1); // A的ASCII码是65
      }
      return problemId;
    }
  };

  const renderProblemColumn = (problemId: string) => {
    return {
      title: `题目 ${getProblemDisplayLabel(problemId)}`,
      dataIndex: ['submission_info', problemId],
      key: `problem_${problemId}`,
      align: 'center' as const,
      render: (info: any, record: ContestRankingItem) => {
        if (!info) return null;
        
        if (contest.rule_type === 'ACM') {
          return (
            <div className={styles.problemCell}>
              {info.is_ac ? (
                <div className={styles.acProblem}>
                  <Tag color="green">AC</Tag>
                  <div>{formatTime(info.ac_time)}</div>
                  {info.error_number > 0 && (
                    <div className={styles.errorCount}>(-{info.error_number})</div>
                  )}
                </div>
              ) : (
                <div className={styles.notAcProblem}>
                  {info.error_number > 0 && (
                    <Tag color="red">-{info.error_number}</Tag>
                  )}
                </div>
              )}
            </div>
          );
        } else {
          // OI赛制直接显示分数
          const score = info;
          return (
            <div className={styles.problemCell}>
              <Tag color={score > 0 ? 'green' : 'default'}>
                {score}
              </Tag>
            </div>
          );
        }
      },
    };
  };

  const columns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      width: 80,
      render: (text: string, record: any, index: number) => renderRankIcon(index + 1),
    },
    {
      title: '用户名',
      key: 'username',
      render: (record: ContestRankingItem) => (
        <Space>
          <Text>{record.user.username}</Text>
          {record.profile.real_name && (
            <Text type="secondary">({record.profile.real_name})</Text>
          )}
        </Space>
      ),
    },
    {
      title: '学校',
      dataIndex: ['profile', 'school'],
      key: 'school',
    },
    {
      title: contest.rule_type === 'ACM' ? '总用时' : '总分',
      key: 'score',
      render: (record: ContestRankingItem) => (
        <div>
          {contest.rule_type === 'ACM' ? (
            <div>
              <Tag color="blue">{record.accepted_number}题</Tag>
              <div>{formatTime(record.total_time || 0)}</div>
            </div>
          ) : (
            <Tag color="blue">{record.total_score}</Tag>
          )}
        </div>
      ),
    },
    ...problemIds.map(problemId => renderProblemColumn(problemId)),
  ];

  return (
    <div className={styles.container}>
      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={rankings.map((item, index) => ({ ...item, rank: index + 1 }))}
          rowKey="id"
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: handlePageChange,
            onShowSizeChange: handlePageChange,
          }}
          scroll={{ x: 'max-content' }}
          className={styles.tableCell}
          onRow={(record, index) => {
            let className = '';
            if (index === 0) className = styles.firstRankRow;
            else if (index === 1) className = styles.secondRankRow;
            else if (index === 2) className = styles.thirdRankRow;
            
            return {
              className,
            };
          }}
          components={{
            header: {
              wrapper: props => <thead className={styles.tableHeader} {...props} />
            }
          }}
        />
      </Spin>
    </div>
  );
};

export default ContestRanking; 